import { reactive, ref, unref } from "vue";
import type { Ref } from "vue"


// api就是传进来的参数 api.admin.getAdminList
// queryParams参数
function useTable<P, R extends {
    list: any;
    pageNum: number;
    pageSize: number;
    total: number;
    totalPage: number
}>(api: (data?: P) => Promise<R>, queryParams?: P) {
    // 分页器
    let pagination = reactive({
        pageNum: 1,
        pageSize: 10,
        total: 0,
        totalPage: 0
    })
    // 获取data的列表
    let tableData: Ref<R["list"]> = ref([])
    async function getTableData() {
        // queryParams在为对象的情况下才能结构合并到对象里面
        // console.log(queryParams); //传进来的queryParams已经变成了一个ref类型
        let normalQueryParams = {} as P
        if (typeof queryParams === "object") {
            for (let key in queryParams) {
                // console.log(key);
                normalQueryParams[key] = unref(queryParams[key])
            }
        }
        // console.log(normalQueryParams);

        let result = await api({
            pageNum: pagination.pageNum,
            pageSize: pagination.pageSize,
            ...normalQueryParams, //最终要合并的应该是一个普通的对象
        })
        console.log(result);
        console.log(pagination);

        tableData.value = result.list
        pagination.pageNum = result.pageNum
        pagination.pageSize = result.pageSize
        pagination.total = result.total
        pagination.totalPage = result.totalPage
        // console.log(tableData.value);
    }
    getTableData()
    // 每页条数发生变化时触发
    let handleSizeChange = (val: number) => {
        console.log(val, 1111);
        pagination.pageSize = val
        getTableData()
    }
    // 改变当前页数
    let handleCurrentChange = (val: number) => {
        console.log(val);
        pagination.pageNum = val
        getTableData()
    }
    // console.log("useTable");

    return { tableData, pagination, handleSizeChange, handleCurrentChange, getTableData }
}

export default useTable